package com.ctsi.ssdc.security;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.ctsi.ssdc.admin.domain.CscpUser;
import com.ctsi.ssdc.admin.service.CscpMenusService;
import com.ctsi.ssdc.admin.service.UserService;

/**
 * Authenticate a user from the database.
 */

public class CscpUserDetailsService implements UserDetailsService {

	private final Logger log = LoggerFactory.getLogger(CscpUserDetailsService.class);

	private final UserService userService;
	private final CscpMenusService cscpMenusService;

	public CscpUserDetailsService(UserService userService, CscpMenusService cscpMenusService) {
		this.userService = userService;
		this.cscpMenusService = cscpMenusService;
	}

	@Override
	public UserDetails loadUserByUsername(final String login) {
		log.debug("Authenticating {}", login);

		return userService.findByUserName(login).map(user -> createSpringSecurityUser(login, user))
				.orElseThrow(() -> new UsernameNotFoundException("User  " + login + " was not found"));

	}

	protected CscpUserDetail createSpringSecurityUser(String lowercaseLogin, CscpUser user) {
		// if (!user.getActivated()) {
		// throw new UserNotActivatedException("User " + lowercaseLogin + " was
		// not
		// activated");
		// }

		List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

		cscpMenusService.findByUserId(user.getId()).forEach(menu -> {

			if (StringUtils.isNotEmpty(menu.getPermissionCode())) {
				grantedAuthorities.add(new SimpleGrantedAuthority(menu.getPermissionCode()));
			}

		});

		return new CscpUserDetail(user.getId(), user.getUsername(), user.getPassword(), grantedAuthorities);
	}
}
